﻿using System.Linq;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Aspects;
using Orchard.ContentManagement.Handlers;
using Orchard.Data;
using Orchard.Environment;
using Piedone.ContentTemplates.Models;
using Piedone.ContentTemplates.Services;

namespace Piedone.ContentTemplates.Handlers
{
    public class TemplatePartHandler : ContentHandler
    {
        public TemplatePartHandler(
            IRepository<TemplatePartRecord> repository,
            Work<ITemplateService> templateService,
            Work<IContentManager> contentManagerWork,
            Work<ITemplateService> templateServiceWork)
        {
            Filters.Add(StorageFilter.For(repository));

            OnActivated<TemplatePart>((context, part) =>
            {
                part.TemplateLoadersField.Loader(() => templateService.Value.GetLoadersFor(part).Select(loader => new TemplatePart.TemplateLoader { Descriptor = loader.Descriptor }).ToList());
                part.TemplateField.Loader(() => contentManagerWork.Value.Get(part.TemplateId, VersionOptions.Latest));
                part.AvailableTemplatesField.Loader(() => templateServiceWork.Value.GetTemplatesQuery().ForPart<ContentPart>().ForVersion(VersionOptions.Latest).List<ContentItem>().OrderBy(item => item.As<ITitleAspect>().Title).ToList());
            });

            OnUpdated<TemplatePart>((context, part) =>
            {
                var selectedLoaderNames = part.TemplateLoaders.Where(provider => provider.IsSelected).Select(provider => provider.Name);

                if (!selectedLoaderNames.Any()) return;

                foreach (var loader in templateServiceWork.Value.GetLoadersFor(part.Template, part))
                {
                    if (selectedLoaderNames.Contains(loader.Descriptor.Name))
                    {
                        loader.LoadFromTemplate(part.Template, part);
                    }
                }
            });
        }
    }
}